<template>
  <el-table
    ref="table"
    border
    :data="tableData3"
    size="mini"
    style="width: 100%"
    @selection-change="handleSelectionChange"
    @sort-change="sortChange"
  >
    <el-table-column type="selection" v-show="root !== 'curupdate'" width="50"> </el-table-column>
    <el-table-column :label="$t('km.kPointTitle')" show-overflow-tooltip>
      <template scope="scope">
        <div class="titlecolor" @click="handleContent(scope.$index, scope.row)">{{ scope.row.title }}</div>
      </template>
    </el-table-column>
    <el-table-column prop="createTime" sortable :label="$t('public.createTime')" show-overflow-tooltip> </el-table-column>
    <el-table-column prop="date" sortable :label="$t('km.updateTime')" show-overflow-tooltip> </el-table-column>
    <el-table-column prop="name" :label="$t('km.editor')" show-overflow-tooltip> </el-table-column>
    <el-table-column :label="$t('km.status')" show-overflow-tooltip>
      <template scope="scope">
        <span v-if="scope.row.status === 'notExpired'">{{ $t('km.notEffective') }}</span>
        <span v-else-if="scope.row.status === 'invalid'">{{ $t('km.invalid') }}</span>
        <span v-else>{{ $t('km.valid') }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="validityPeriod" :label="$t('km.validity')" show-overflow-tooltip>
      <template scope="scope">
        <span>{{ scope.row.validityPeriod | getTimeFun }}</span>
      </template>
    </el-table-column>
    <el-table-column :label="$t('km.label')" show-overflow-tooltip>
      <template scope="scope">
        <span>{{ scope.row.tagList | getTagsName(kmTagsObj) }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="clickrate" sortable :label="$t('km.clickRate')" show-overflow-tooltip> </el-table-column>
    <el-table-column
      :context="_self"
      v-if="root !== 'curupdate' && hasManage"
      :label="$t('public.operate')"
      width="100"
    >
      <template scope="scope">
        <div>
          <i class="icon iconfont icon-beizhu" @click="handleEdit(scope.$index, scope.row)"></i>
          <i
            class="icon iconfont icon-guanbi"
            @click="handleDelete(scope.$index, tableData3)"
            v-if="!forbiddenDelete"
          ></i>
          <i
            class="icon iconfont icon-zhiding"
            v-if="!scope.row.placeTop && forbiddenPlaceTop"
            @click="handlePlaceUp(scope.$index, scope.row)"
          ></i>
          <i
            class="icon iconfont icon-xiazai"
            v-if="scope.row.placeTop && forbiddenPlaceTop"
            @click="handlePlaceDown(scope.$index, scope.row)"
          ></i>
        </div>
      </template>
    </el-table-column>
  </el-table>
</template>
<script>
import bus from '@/store/eventBus'
export default {
  props: [
    'data',
    'KmType',
    'tableData',
    'currentpage',
    'recent',
    'root',
    'hasManage',
    'forbiddenDelete',
    'forbiddenPlaceTop'
  ],
  filters: {
    getTimeFun(val) {
      if (val && val.length) {
        return val[0] + ' ~ ' + val[1]
      }
      return '--'
    },
    getTagsName(tags, kmTagsObj) {
      let tagName = ''
      if (tags && tags.length) {
        tags.forEach((item, index) => {
          if (kmTagsObj[item] && kmTagsObj[item].name) {
            tagName += index === tags.length - 1 ? kmTagsObj[item].name : kmTagsObj[item].name + '、'
          }
        })
      } else {
        tagName = '--'
      }
      return tagName
    }
  },
  data() {
    return {
      tableData3: [],
      multipleSelection: [],
      recentShow: false,
      kmTagsObj: {}
    }
  },
  mounted() {
    bus.$on('kmDetailClearSort', (msg) => {
      this.$refs.table.clearSort()
    })
    this.$store.dispatch('queryKmTags', {}).then((resp) => {
      if (resp.list) {
        resp.list.forEach((i) => {
          this.kmTagsObj[i._id] = i
        })
      }
    })
  },
  beforeDestroy() {
    //      解除bus事件监听
    bus.$off('kmDetailClearSort')
  },
  watch: {
    //      $route (to, from) {
    //        if (to.path.split('/')[4] === 'curupdate') {
    //          this.queryRecentList()
    //        } else {
    //          to.params.kmId && this.queryItemList()
    //        }
    //      },
    tableData(val1, val2) {
      this.tableData3 = val1
      //        this.searchData(val1)
    },
    currentpage(val1, val2) {
      // this.queryItemList()
    },
    recent() {
      this.queryRecentList()
    }
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val
      this.$emit('multipleSelection', this.multipleSelection)
    },
    clearSelection() {
      this.$refs.table.clearSelection()
    },
    checkAll() {
      this.tableData3.forEach((item) => {
        this.$refs.table.toggleRowSelection(item, true)
      })
    },
    handleEdit(index, row) {
      this.$emit('editBtn', row)
    },
    handleContent(index, row) {
      this.$emit('show', row)
    },
    sortChange(data) {
      this.$emit('sorTableFun', data)
    },
    handleDelete(index, row) {
      // 删除知识点
      let currenTitle = row[index].title.substring(0, 15)
      this.$confirm(this.$t('public.confirmCurrent', { currenTitle }), this.$t('public.operate'), {
        confirmButtonText: this.$t('public.confirm'),
        cancelButtonText: this.$t('public.cancel'),
        cancelButtonClass: 'primary_btn',
        confirmButtonClass: 'primary_btn',
        type: 'warning'
      })
        .then(() => {
          let data = {
            _id: row[index]._id,
            kmType: this.KmType
          }
          this.$store.dispatch('delItem', data).then((res) => {
            if (res.success) {
              this.$store.commit('km/REFRESH_RIGHT', { type: 'cache' })
              this.$message({
                type: 'success',
                message: this.$t('km.deleteSucc')
              })
            }
          })
        })
        .catch(() => {})
    },
    handlePlaceUp(index, row) {
      this.$emit('handlePlaceTop', row, true)
    },
    handlePlaceDown(index, row) {
      this.$emit('handlePlaceTop', row, false)
    },
    queryItemList() {
      if (this.currentpage < 1 || this.currentpage === '' || this.currentpage == null) {
        this.currentpage = 1
      }
      let data = {
        cid: this.$route.params.kmId,
        kmType: this.KmType,
        id: 'dd',
        page: this.currentpage
      }
      this.$emit('addData', data)
      let obj = {}
      return this.$store.dispatch('queryItemList', data).then(() => {
        let itemList = this.$store.state.km.itemList
        let totalPage = Math.ceil(itemList.count / 10)
        let recentList = itemList.list
        //          let current = ''
        //          if (recentList[0] != null) {
        //            let agents = this.$store.state.session.dicMap.agents
        //            for (let key in agents) {
        //              if (agents[key]._id === recentList[0].publisher) {
        //                current = agents[key].displayName
        //              }
        //            }
        //          }
        let arr = []
        for (let i = 0; i < recentList.length; i++) {
          obj = {
            title: recentList[i].title,
            name: this.getDisplayName(recentList[i].updateUser || recentList[i].publisher),
            date: recentList[i].lastTime,
            createTime: recentList[i].createTime,
            clickrate: recentList[i].hits,
            _id: recentList[i]._id,
            cid: recentList[i].cid,
            kmType: recentList[i].kmType
          }
          arr.push(obj)
        }
        this.tableData3 = arr
        let list = {
          page: this.currentpage,
          totalPage: totalPage,
          count: itemList.count
        }
        this.$emit('pages', list)
      })
    },
    getDisplayName(id) {
      let agent = this.$agentsMap() || {}
      return agent[id] ? agent[id].displayName : ''
    },
    queryRecentList() {
      let recentList = this.recent
      //        let current = ''
      //        if (recentList[0] != null) {
      //          let agents = this.$store.state.session.dicMap.agents
      //          for (let i in agents) {
      //            if (agents[i]._id === recentList[0].publisher) {
      //              current = agents[i].displayName
      //            }
      //          }
      //        }
      let obj = {}
      let arr = []
      for (let i = 0; i < recentList.length; i++) {
        obj = {
          title: recentList[i].title,
          name: this.getDisplayName(recentList[i].updateUser || recentList[i].publisher),
          date: recentList[i].lastTime,
          createTime: recentList[i].createTime,
          clickrate: recentList[i].hits,
          _id: recentList[i]._id,
          cid: recentList[i].cid,
          kmType: recentList[i].kmType,
          tagList: recentList[i].tagList,
          status: recentList[i].status,
          validityPeriodType: recentList[i].validityPeriodType,
          validityPeriod: recentList[i].validityPeriod
        }
        arr.push(obj)
      }
      this.tableData3 = arr
    },
    searchData(val1) {
      if (val1 != null) {
        console.dir(val1)
        let arr = []
        let list = val1
        for (let i = 0; i < list.length; i++) {
          let obj = {
            title: list[i].title,
            name: '',
            date: '',
            clickrate: '',
            _id: list[i]._id,
            cid: list[i].cid
          }
          arr.push(obj)
        }
        this.tableData3 = arr
      }
    }
  }
}
</script>
<style lang="stylus" scoped>
@import "../../../../assets/common.styl";
.el-table
  color $cf-level4
  .icon-beizhu
  .icon-zhiding
  .icon-xiazai
    color $c-main
    margin-right 6px
    cursor pointer
  .icon-guanbi
    color $c-pink
    cursor pointer
.titlecolor
  color $c-main
  cursor pointer
</style>
